package com.yand.thinkingInJava.thinkingInJava21.threadcooperation;


import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;


/**
 * wait() 等待会释放锁，，，，
 *
 *
 *
 * 小汽车 一个简单的模拟，抛光与打蜡， 先抛光在打蜡
 */
class Car{


    //抛光与打蜡状态， true 打蜡，抛光等待，false 抛光   打蜡等待   默认为false 所以先抛光
    private boolean waxOn = false;

    //打蜡
    public synchronized void waxed() throws InterruptedException{
        waxOn = true;
        notifyAll();
        wait();
    }

    //抛光
    public synchronized void buffed() throws InterruptedException{
        waxOn = false;
        notifyAll();
        wait();
    }


    //等待打蜡
    public synchronized void waitForWaxing() throws InterruptedException{
        if(waxOn == false){
            wait();
        }
    }


    //等待抛光
    public synchronized void waitForBuffing() throws InterruptedException{
        if(waxOn == true){
            wait();
        }
    }
}


//打蜡线程
class WaxOn implements Runnable{

    private Car car;
    public WaxOn(Car c){
        this.car = c;
    }

    @Override
    public void run() {
       try{
           while(!Thread.interrupted()){
               System.out.println("打蜡!");
               TimeUnit.MILLISECONDS.sleep(200);
               car.waxed();
               //打蜡等待准备抛光
               car.waitForBuffing();
           }



       }catch (InterruptedException e){
           System.out.println("Exiting via interrupt");
       }
           System.out.println("Ending Wax On task");
    }
}



//打蜡结束 抛光线程
class WaxOfff implements Runnable{

    private Car car;

    public WaxOfff(Car c){
        this.car = c;
    }


    @Override
    public void run() {
        try{
            while(!Thread.interrupted()){
                System.out.println("抛光！");
                TimeUnit.MILLISECONDS.sleep(200);
                car.buffed();
                car.waitForWaxing();
            }



        }catch (InterruptedException e){
            System.out.println("Exiting via interrupt");
        }
        System.out.println("Ending Wax Off task");
    }
}



public class WaxOMatic {

    public static void main(String [] args) throws InterruptedException {
         Car c = new Car();
         ExecutorService exec = Executors.newCachedThreadPool();
         exec.execute(new WaxOfff(c));
         exec.execute(new WaxOn(c));
         TimeUnit.SECONDS.sleep(5);
         exec.shutdownNow();
    }


}
